const { generateRandomNews } = require('./data');
const newsList = generateRandomNews(30);

// 根据id修改收藏状态
function updateCollectedNewsList(id) {
  for (let i = 0; i < newsList.length; i++) {
    if (newsList[i].id == id) {
      newsList[i].collected = !newsList[i].collected;
      break; 
    }
  }
}

//根据类别获取新闻
function getHomeNewsList(type){
  const newsList = generateRandomNews(30);
  var list = []
  for(let i = 0; i < newsList.length; i++) {
    if(newsList[i].category == type){
      list.push(JSON.parse(JSON.stringify(newsList[i])))
    }
  }
  return list;
}

//获取新闻详情数据
function getNewsDetail(id) {
  let data = {
    code : '404',
    msg : 'not found',
    data : {}
  }
  for (const iterator of newsList) {
    if(id == iterator.id){
      data = {
        code : '200',
        msg : 'success',
        data : JSON.parse(JSON.stringify(iterator))
      }
      return data;
    }
  } 
  return data;
}

//根据收藏新闻
function getCollectedNewsList(){
  var list = []
  for(let i = 0; i < newsList.length; i++) {
    if(newsList[i].collected == true){
      list.push(JSON.parse(JSON.stringify(newsList[i])))
    }
  }
  return list;
}

module.exports = {
  getHomeNewsList,
  getNewsDetail,
  getCollectedNewsList,
  updateCollectedNewsList
};
